import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;

public class ChatClient extends UnicastRemoteObject implements ChatBack
{

    private String nick;

    public void send(String src,String msg)
    {
	System.out.println("From "+src+" : "+msg);
    }

    public ChatClient() throws RemoteException
    {
	super();
	nick = new String();
    }
    
    public void run(Chat chat) throws RemoteException
    {    
	Scanner scanInput = new Scanner(System.in);
	String buffer = new String();
	int size;
	while(true)
	    {
		buffer=scanInput.nextLine();
		size=buffer.length();
		//System.out.println(buffer);
		System.out.flush();
		if (buffer.startsWith("/disconnect"))
		    {
			chat.disconnect(nick,this);
			System.out.println(this.nick+" Disconnected\n");
			chat.send(nick,"Disconnected\n");
			System.exit(1);
		    }
		if (buffer.startsWith("/connect"))
		    
		    {
			nick = buffer.substring(9,size);
			System.out.println(this.nick+" Connected\n");
			chat.send(nick,"Connected\n");
			chat.connect(nick,this);
		    }
		
		else
		    {
			chat.send(nick,buffer);
		    }
	    }
	
    }
    
    public static void main(String args[]) { 

	if (args.length < 2) {
	    System.out.println("Usage: ChatClient host port");
	    System.exit(1);
	}

	try {
	    String host = args[0];
	    String port = args[1];
	    String url = "rmi://" + host +":" + port + "/Chat"; 
	    // Look up for the Remote Object Chat from RMI registry 
	    Chat chat = (Chat)Naming.lookup(url);
	    ChatClient chatClient = new ChatClient();
	    chatClient.run(chat);
	    
	} catch (Exception e) { 
	    System.out.println("ChatClient exception: " + e.getMessage()); 
	    e.printStackTrace(); 
	} 
	
    } 
}
